﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Script.Serialization;
using System.Xml;
using System.Xml.Serialization;
using bmapi.HelperClass;
using bmapi.Models.CADModel;
using bmapi.Models.DataEntity;
using ICSharpCode.SharpZipLib.Zip;
using Newtonsoft.Json;
using static bmapi.Models.ShowModel;

namespace bmapi.Controllers
{
    public class ValuesController : PageController
    {
        private JavaScriptSerializer m_jss = new JavaScriptSerializer();
        List<person> m_persons = new List<person>();
        // GET api/values  
        [HttpGet,Route("api/values")]
        public void Get(string url=null,string paras=null)
        {
            string filename = "dhfdj.jhj";
            string dirName = filename.Substring(0, filename.LastIndexOf("."));

            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = null;
            //if (url.Contains("fwq2012/bmapi"))
            if (url.Contains("win2008/bmapi"))
                request = (HttpWebRequest)WebRequest.Create(url);
            else
                request = (HttpWebRequest)WebRequest.Create(url + ".json");
            request.Method = "POST";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";
            byte[] buffer = encoding.GetBytes(paras);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                reader.ReadToEnd();
            }
        }

        #region 申请
        [HttpPost, Route("cad33/apply")]
        public string Finish(dynamic json)
        {
            WriteLog("cad33/Finish", "json:" + json.ToString(), true);
            if (json == null)
                return"没有可执行参数";

            int loginid = GetCrrentIDByToken();
            User user = GetUserByLoginID(loginid);
            if (user == null)
                return "不存在当前工号为" + loginid + "的用户";
            try
            {
                int orderid = Convert.ToInt32(json.id);
                string sql = "select Order_tb.id,Order_tb.name as name,Model_tb.id as ModelId,Model_tb.name as modelName,o_creater_id,finish_time,bind_id,erp_id,erp_name,LSH,quantity,erp_custname,mCode,mColor,rank,nature,remark,width from Order_tb join Model_tb on o_model_id = Model_tb.id where Order_tb.id = @orderid";
                SQLCommand sc = new SQLCommand(sql, "@orderid", orderid);
                MyOrder order = AssistFun.DataRowToObject<MyOrder>(sc.ExecuteOneRow());
                if (order == null)
                {
                    WriteDebug("cad33/Finish", "该生产单不存在");
                    return "该生产单不存在";
                }
                else
                {
                    return GetOrderDetailByOrderId(order, user);
                }
            }
            catch (Exception ex)
            {
                WriteDebug("cad33/Finish8 异常：", ex.Message);
            }

            return  "OK";
        }


        /// <summary>
        /// 根据id取得订单详情    
        /// </summary>
        /// <param name="obj"></param>
        private string GetOrderDetailByOrderId(MyOrder myorder, User user)
        {
            try
            {
              
                SQLCommand sc = new SQLCommand("select key_val from System_tb where key_name='Url'");
                string url = sc.ExecuteScalar();
                if (url == null)
                    return "请先由管理员设置好数据访问地址";
                string res = RequestUrl.NoSafePost(url + "/getQbcScd", m_jss.Serialize(new { pageSize = 1, pageNo = 50, PRIMARYID = myorder.erp_id }));
                res = AssistFun.RemoveChar(res, url);

                ERPOrderDetail orderdetail = m_jss.Deserialize<ERPOrderDetail>(res);
                List<string> LTName = new List<string>();
                //量体信息
                List<DetailInfo> LTInfo = new List<DetailInfo>();
                LTName.AddRange(orderdetail.data.data.LT_NAME);
                LTInfo.AddRange(orderdetail.data.data.LTINFOD);
                int pages = Convert.ToInt32(orderdetail.data.totalPage);
                int rows = Convert.ToInt32(orderdetail.data.totalRow);
                if (pages > 1)
                {
                    for (int i = 1; i < pages; i++)
                    {
                        res = RequestUrl.NoSafePost(url + "/getQbcScd", m_jss.Serialize(new { pageSize = 1 + i, pageNo = 50, PRIMARYID = myorder.erp_id }));
                        res = AssistFun.RemoveChar(res, url);
                        ERPOrderDetail nextOrderDetails = m_jss.Deserialize<ERPOrderDetail>(res);
                        //合并数据
                        LTInfo.AddRange(nextOrderDetails.data.data.LTINFOD);
                    }
                }
                //请求数据与返回数据一致
                if (LTInfo.Count == rows)
                {
                    if (LTInfo.Count != myorder.quantity)
                        return "获取人数" + LTInfo.Count + "不等于订单人数" + myorder.quantity;
                }
                return CreateXml(myorder, LTName, LTInfo, user);
            }
            catch (Exception ex)
            {
                WriteDebug("GetOrderDetailByOrderId", "错误：" + ex.Message);
                return "GetOrderDetailByOrderId -- 错误：" + ex.Message;
            }
        }

        /// <summary>
        /// 创建订单xml文件
        /// </summary>
        /// <param name="order"></param>
        /// <param name="ltName"></param>
        /// <param name="orderDetails"></param>
        private string CreateXml(MyOrder selorder, List<string> ltName, List<DetailInfo> orderDetails, User user)
        {
            try
            {
                if (ltName.Count == 0)
                    return "没有测量部位名";
                else if (orderDetails.Count == 0)
                    return "没有量体数据";
                else
                {
                    td tdxml = CteatXmlData(selorder, ltName, orderDetails);
                    string xml = AssistFun.XmlSerialize(tdxml, Encoding.UTF8);
                    byte[] myByte = Encoding.UTF8.GetBytes(xml);
                    string xmlDir = m_buyiRoot + "\\buyiWork\\" + tdxml.order.orderName;
                    if (!Directory.Exists(xmlDir))
                        Directory.CreateDirectory(xmlDir);
                    WriteDebug("CreateXml", xmlDir);
                    using (FileStream fsWrite = new FileStream(xmlDir + "\\" + tdxml.order.orderName + ".xml", FileMode.OpenOrCreate))
                    {
                        fsWrite.Write(myByte, 0, myByte.Length);
                    };
                }
                return"OK";
            }
            catch (Exception ex)
            {
                WriteDebug("CreateXml", "异常：" + ex.Message);
                return "CreateXml -- 异常：" + ex.Message;
            }

        }

        /// <summary>
        /// 构建订单xml文件数据
        /// </summary>
        /// <param name="selorder"></param>
        /// <param name="ltName"></param>
        /// <param name="orderDetails"></param>
        /// <returns></returns>
        private td CteatXmlData(MyOrder selorder, List<string> ltName, List<DetailInfo> orderDetails)
        {
            try
            {
                td tdxml = new td();
                for (int i = 0; i < orderDetails.Count; i++)
                {
                    person per = new person()
                    {
                        ID =Convert.ToInt32(orderDetails[i].LAB_SIZE_INPUTID),
                        name = orderDetails[i].CUST_NAME,
                        phone = "",
                        remark = orderDetails[i].LT_MEMO,
                        copys = orderDetails[i].QTY.ToString(),
                        sizeName = orderDetails[i].LT_XINGHAO,
                        measureVal = AssistFun.stringToListdouble(orderDetails[i].LY_VAL),
                    };
                    //person per = new person()
                    //{
                    //    ID =  orderDetails[i].LAB_SIZE_INPUTID,
                    //    name = orderDetails[i].CUST_NAME,
                    //    phone = "",
                    //    remark = orderDetails[i].LT_MEMO,
                    //    copys = orderDetails[i].QTY,
                    //    sizeName = orderDetails[i].LT_XINGHAO,
                    //    measureVal = AssistFun.stringToListdouble(orderDetails[i].LY_VAL),
                    //};
                    m_persons.Add(per);
                }
                string name = selorder.name;
                order myorder = new order()
                {
                    modelName = selorder.modelName, //样式名没存
                    orderID = selorder.erp_id,
                    orderName = name,
                    erpName = selorder.erp_name,
                    subName = Convert.ToInt32(name.Remove(0, name.LastIndexOf('-') + 1)),
                    //type = selorder.LT,
                    //style = selorder.STYLE_NO_CODE,
                    number = selorder.quantity,
                    isAlarm = selorder.rank.ToString(),
                    depiction = selorder.remark,
                    schemetype = selorder.nature,
                    overTime = selorder.finish_time.ToString("yyyy-MM-dd HH:mm:ss"),
                    customerName = selorder.erp_custname
                };
                fabric fab = new fabric()
                {
                    code = selorder.mCode,
                    color = selorder.mColor,
                    width = selorder.width.ToString(),
                };
                tdxml.partList = null;
                tdxml.fabricList = new List<fabric>() { fab };
                tdxml.personList = m_persons;
                tdxml.order = myorder;
                tdxml.measureName = ltName;
                return tdxml;
            }
            catch (Exception)
            {

                throw;
            }

        }
        
        #endregion


        #region  海澜接口数据测试


        /// <summary>
        /// 订单查询 
        /// </summary>
        /// <returns></returns>
        [HttpPost,Route("getScheme")]
        public string GetOrder()
        {
            string json = "";
            string path = m_buyiRoot + "\\order.json";
            try
            {                
                StringBuilder sb = new StringBuilder(); 
                using (FileStream fs = new FileStream(path, FileMode.Open))
                {
                    using (StreamReader sr = new StreamReader(fs, Encoding.Default))
                    {
                        json = sr.ReadToEnd();
                        json = json.Replace("\r\n", "").Trim();
                        json = json.Replace(" ", "");
                        json = json.Replace("\r", "");
                        JugeInfo info = new JavaScriptSerializer().Deserialize<JugeInfo>(json);
                    }
                }
            }
            catch (Exception e)
            {
                throw ;
            }           
            return json;
        }
        public class JugeInfo
        {
            public string status { get; set; }
            public string msg { get; set; }
        }
        /// <summary>
        /// 订单详情 
        /// </summary>  
        /// <returns></returns>
        [HttpPost, Route("getQbcScd")]
        public string GetOrderDetail()
        {
            string json = "";
            string path = m_buyiRoot+ "\\detail.json";
            using (FileStream fs = new FileStream(path, FileMode.Open))  //@"E:\海澜\HaiLan\TestData\detail.json"
            {
                using (StreamReader sr = new StreamReader(fs, Encoding.Default))
                {
                    json = sr.ReadToEnd();
                    json = json.Replace("\r\n", "").Trim();
                    json = json.Replace(" ", "");
                }
            }
            return json.Replace("\t","");
        }

        /// <summary>
        /// 样板查询  
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("getQbcYb")]
        public string GetYB()
        {
            string json = "";
            string path = m_buyiRoot + "\\yb.json";
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                using (StreamReader sr = new StreamReader(fs, Encoding.Default))
                {
                    json = sr.ReadToEnd();
                    json = json.Replace("\r\n", "").Trim();
                    json = json.Replace(" ", "");
                }
            }
            return json.Replace("\t", "");
        }
        #endregion
    }
}
